package com.jin.webvideo.mapper;

import com.jin.webvideo.entity.Cache;
import com.jin.webvideo.entity.VideoInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface CacheMapper {
    @Insert("insert into cache(url, location, fileName, status, cacheDate, fileSize, lastVisited, statusDate, cacheType, parserName) values(#{url}, #{location}, #{fileName}, 'new', #{cacheDate}, #{fileSize}, #{lastVisited}, now(), #{cacheType}, #{parserName})")
    public int insert(Cache cache);

    @Select("select url, location, fileName, cacheDate, fileSize, lastVisited, status, statusDate, cacheType from cache where url=#{url} and status in ('canPlay', 'caching', 'new')")
    public Cache selectByUrl(String url);

    @Select("select count(1) from cache where location=#{location}")
    public int hasLocation(String location);

    @Select("select url, location, fileName, cacheDate, fileSize, lastVisited, statusDate from cache where status='canPlay' order by lastVisited asc")
    public List<Cache> listCanplay();

    @Select("select url, status, location, fileName, cacheDate, fileSize from cache where url=#{url}")
    public Cache hasCache(String url);

    @Update("update cache set status='canPlay', fileSize=#{fileSize}, statusDate=now() where url=#{url}")
    public int canPlay(String url, double fileSize);

    @Update("update cache set status=#{status}, cacheDate=now(), statusDate=now() where url=#{url}")
    public int updateStatus(String url, String status);

    @Update("update cache set status=#{status}, cacheDate=now(), statusDate=now(), cacheType=#{cacheType}, parserName=#{parserName} where url=#{url}")
    public int updateCache(String url, String status, int cacheType, String parserName);

    @Update("update cache set lastVisited=now() where url=#{url}")
    public int visited(String url);

    // 查找最后访问时间大于lastVisited 且 缓存时间小于cacheDate 的可用数据
    @Select("select vi.platform, vi.docid, vi.ordin from cache c join videoInfo vi on c.url=vi.url where status='canPlay' and cacheType=1 and lastVisited > #{lastVisited} and cacheDate < #{cacheDate} and parserName=#{parserName}")
    public List<VideoInfo> needBkUpdate(String lastVisited, String cacheDate, String parserName);
}
